package com.ljd.repository.impl;

import com.ljd.entity.Book;
import com.ljd.entity.BookCase;
import com.ljd.entity.Borrow;
import com.ljd.repository.BookRepository;
import com.ljd.utils.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {
    @Override
    public List<Book> findAllBooks(int index, int limit) {
        Connection conn = null;
        String sql = "select * from book,bookcase where book.bookcaseid=bookcase.id limit ?,?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Book> list = new ArrayList<Book>();
        conn = JDBCTools.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, index);
            ps.setInt(2, limit);
            rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Book(rs.getInt("book.id"),
                        rs.getString("book.name"),
                        rs.getString("author"),
                        rs.getString("publish"),
                        rs.getInt("pages"),
                        rs.getDouble("price"),
                        new BookCase(rs.getInt("bookcase.id")
                                , rs.getString("bookcase.name"))));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }


    @Override
    public Integer getCount() {
        Connection conn = null;
        String sql = "select count(*) from book,bookcase " +
                "where book.bookcaseid=bookcase.id";
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer count = null;

        conn = JDBCTools.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }
}
